package com.mc.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.mc.model.DdType;
import com.mc.model.Path;
import com.mc.model.data_download;
import com.mc.service.IDataService;
import com.mc.service.IDdtypeService;
import com.mc.utils.PathUtil;
import com.mc.utils.StringUtil2;
import com.mc.utils.XMLParserUtil;

@Controller
@RequestMapping("/filedownload")
public class FileDownloadAction {

	@Autowired private IDataService dataService;
	@Autowired private IDdtypeService ddtypeService;
	private Path path = null;
	private String TITLE;
	/**
	 * 
	 * @param modelMap
	 * @return 文件管理界面
	 */
	@RequestMapping("/filedownloadindex/{pageNum}")
	public String bkpy(@PathVariable("pageNum") int num,ModelMap modelMap)
	{
		int perPage = 8;// 每页显示新闻条数
		//ModelAndView mav = new ModelAndView();
		int rowCount = dataService.selectAllCount();
		int pagecount = rowCount % perPage;
		if (pagecount == 0)// 偶数条记录
			modelMap.addAttribute("pageCount", rowCount / perPage);
		else
			// 奇数条记录
			modelMap.addAttribute("pageCount", rowCount / perPage + 1);
		List<data_download> nab = dataService.selectAllLimit((num-1)*perPage, perPage);
		
		List<DdType> ddts = ddtypeService.allddtype();
		modelMap.addAttribute("ddts",ddts);
		modelMap.addAttribute("pageNow", num);
		modelMap.addAttribute("allnews", nab);
		path = PathUtil.setPathParams(new String[]{"PackageName:Filedownload","ViewName:zcwd","ViewTitle:文件下载","smenu:Filedownload","mmenu:Filedownloadindex","mmmenu:all"});				
		return PathUtil.returnStr(path, modelMap);
	}
	/**
	 * 
	 * @param filename 需要下载的文件名称
	 * @param response 
	 */
	@RequestMapping("/download")  
    public void downloadFile(@RequestParam("filename")String filename,HttpServletResponse response){  
        response.setCharacterEncoding("utf-8"); 
        System.out.println(filename);
        response.setContentType("multipart/form-data"); 
        Map<String,String> filepro = XMLParserUtil.getInstance().ParserUtil("file.xml");
        String urlHeader = StringUtil2.getInstance().getPhysicsPath(filepro.get("filepath"));
        String realFileName =urlHeader+File.separator+ filename ;
        response.setHeader("Content-Disposition", "attachment;fileName="+filename);  
        try {  
            File file=new File(realFileName);  
             
            InputStream inputStream=new FileInputStream(file);  
            OutputStream os=response.getOutputStream();  
            byte[] b=new byte[1024];  
            int length;  
            while((length=inputStream.read(b))>0){  
                os.write(b,0,length);  
            }  
            inputStream.close();  
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }
	/**
	 * 
	 * @param id 文件额理性id
	 * @param num 当前页大小
	 * @param modelMap
	 * @return 展示文件的页面
	 */
	@RequestMapping("/filedownloadindex_{ddtypeid}/{pageNum}")
	public String downloadbyddtype(@PathVariable("ddtypeid")int id,@PathVariable("pageNum") int num,ModelMap modelMap)
	{
		int perPage = 8;// 每页显示新闻条数
		//ModelAndView mav = new ModelAndView();
		int rowCount = dataService.countofddbyddtype(id);
		int pagecount = rowCount % perPage;
		if (pagecount == 0)// 偶数条记录
			modelMap.addAttribute("pageCount", rowCount / perPage);
		else
			// 奇数条记录
			modelMap.addAttribute("pageCount", rowCount / perPage + 1);
		List<data_download> nab = dataService.selectbyddtype(id,(num-1)*perPage, perPage);
		DdType ddType = ddtypeService.selectByPrimaryKey(id);
		List<DdType> ddts = ddtypeService.allddtype();
		modelMap.addAttribute("ddts",ddts);
		modelMap.addAttribute("pageNow", num);
		modelMap.addAttribute("allnews", nab);
		modelMap.addAttribute("ddtypeid",id);
		path = PathUtil.setPathParams(new String[]{"PackageName:Filedownload","ViewName:downloadbyddtype","ViewTitle:文件下载","smenu:Filedownload","mmenu:"+ddType.getDdtypeName(),"mmmenu:"+id});				
		return PathUtil.returnStr(path, modelMap);
	}
	/**
	 * 
	 * @param title 进行模糊查询的文件名称
	 * @param modelMap
	 * @param num 检索界面的当前页
	 * @return 检索页面
	 */
	@RequestMapping("/search/{pageNum}")
	public String search(@RequestParam(value= "title",required=false)String title,ModelMap modelMap,@PathVariable("pageNum") int num){
		if(title!=null){
			TITLE=title;
		}
		
		int perPage = 8;// 每页显示新闻条数
		//ModelAndView mav = new ModelAndView();
		//System.out.println(title);
		int rowCount = dataService.countofbytitlelike(TITLE);
		int pagecount = rowCount % perPage;
		if (pagecount == 0)// 偶数条记录
			modelMap.addAttribute("pageCount", rowCount / perPage);
		else
			// 奇数条记录
			modelMap.addAttribute("pageCount", rowCount / perPage + 1);
		List<data_download> nab = dataService.selectbytitlelike(TITLE,(num-1)*perPage, perPage);
		
		List<DdType> ddts = ddtypeService.allddtype();
		modelMap.addAttribute("ddts",ddts);
		modelMap.addAttribute("pageNow", num);
		modelMap.addAttribute("allnews", nab);
		path = PathUtil.setPathParams(new String[]{"PackageName:Filedownload","ViewName:searchresults","ViewTitle:文件下载","smenu:Filedownload","mmenu:检索结果","mmmenu:1"});				
		return PathUtil.returnStr(path, modelMap);
	}
	
}
